package com.wh.blog.utils;

import com.wh.blog.constant.Constants;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtParser;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.io.Decoders;
import io.jsonwebtoken.io.Encoders;
import io.jsonwebtoken.security.Keys;
import lombok.extern.slf4j.Slf4j;

import javax.crypto.SecretKey;
import java.security.Key;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Slf4j
public class JwtUtils {

    //过期毫秒时⻓ 30分钟
    public static final long Expiration = 30 * 60 * 1000;
    //密钥
    private static final String secretString = "dVnsmy+SIX6pNptQdeclDSJ26EMSPEIhvZYKBTTug4k=";
    //⽣成安全密钥
    private static final SecretKey KEY = Keys.hmacShaKeyFor(Decoders.BASE64.decode(secretString));

    public static String genJwt(Map<String, Object> claim) {
        String token = Jwts.builder()
                .setClaims(claim) //⾃定义内容(负载)
                .setIssuedAt(new Date())// 设置签发时间
                .setExpiration(new Date(System.currentTimeMillis() +
                        Expiration)) //设置过期时间
                .signWith(KEY) //签名算法
                .compact();
        return token;
    }


    /**
     * 校验token
     * Claims 为 null 表示校验失败
     */
    public static Claims parseToken(String token) {
        JwtParser build = Jwts.parserBuilder().setSigningKey(KEY).build();
        Claims claims = null;
        try {
            claims = build.parseClaimsJws(token).getBody();
        } catch (Exception e) {
            log.error("解析token失败, token:{}", token);
            return null;
        }
        log.info("claims:{}", claims);
        return claims;
    }

    public static Integer getIdByToken(String token) {
        Claims claims = parseToken(token);
        if (claims != null) {
            Integer userId = (Integer) claims.get(Constants.TOKEN_ID);
            if (userId > 0) {
                return userId;
            }
        }
        return null;
    }

}
